package com.dianrui.agent.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.dianrui.agent.R;
import com.dianrui.agent.adapter.DeviceListAdapter;
import com.dianrui.agent.bean.DeviceList;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshListView;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author Administrator
 */
public class SearchDeviceActivity extends BaseActivity {
    private int pageIndex = 1;
    private List<DeviceList> vehicleListAll = new ArrayList<>();
    private List<String> qrList = new ArrayList<>();
    private DeviceListAdapter deviceListAdapter;

    @BindView(R.id.search_list)
     ListView deviceList;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;
    @BindView(R.id.search_edit_content)
    EditText searchEditContent;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_search_deivce;
    }

    @Override
    public void initView() {
        deviceListAdapter = new DeviceListAdapter(SearchDeviceActivity.this, vehicleListAll);
        deviceList.setAdapter(deviceListAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getDeviceList(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                getDeviceList(false);
                refreshLayout.finishLoadMore();
            }
        });
        deviceListAdapter.setOndeviceClickListener(new DeviceListAdapter.DeviceClickListener() {


            @Override
            public void showLocation(String usestatus,String glat, String glng, String number, String vehicle_status, int battery) {
                Intent intent = new Intent(SearchDeviceActivity.this, ShowLocationActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("lat", glat);
                bundle.putString("lng", glng);
                bundle.putString("number", number);
                bundle.putString("usestatus", usestatus);
                bundle.putString("vehicle_status", vehicle_status);
                bundle.putInt("battery", battery);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void ClickInfo(String vehicleId) {
                startActivity(new Intent(SearchDeviceActivity.this, DeviceInfoActivity.class)
                        .putExtra("vehicleId", vehicleId));
            }

            @Override
            public void showCode(String qrUrl) {
                startActivity(new Intent(SearchDeviceActivity.this, BigImagesActivity.class)
                        .putExtra("qrImages", qrUrl));

            }
        });
        searchEditContent.setHint("请输入设备编号");
        searchEditContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                getDeviceList(true);
            }
        });

    }

    private void getDeviceList(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex = 1;
        }
        JsonObject deviceListJson = new JsonObject();
        deviceListJson.addProperty("type_id", "2");
        deviceListJson.addProperty("keywords", searchEditContent.getText().toString());
        deviceListJson.addProperty("p", pageIndex);
        StringBuilder deviceListBuilder=new StringBuilder();
        deviceListBuilder.append(SharedUtil.getUrl()).append(Url.DEVICE_LIST);
        OkHttpRequest.getInstance().postTokenRequests(deviceListBuilder.toString(), deviceListJson.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (isRfresh) {
                    vehicleListAll.clear();
                }
                if (!StringUtils.isEmpty(result) && !isFinishing()) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            if (qrList != null) {
                                qrList.clear();
                            }
                            JSONArray vehicleLists = jsonObject.optJSONObject("data").optJSONArray("vehicle_list");
                            if (vehicleLists.length() > 0) {
                                for (int i = 0; i < vehicleLists.length(); i++) {
                                    DeviceList deviceList = new DeviceList();
                                    deviceList.vehicle_id = vehicleLists.optJSONObject(i).optString("vehicle_id");
                                    deviceList.number = vehicleLists.optJSONObject(i).optString("number");
                                    deviceList.device = vehicleLists.optJSONObject(i).optString("device");
                                    deviceList.vehicle_status = vehicleLists.optJSONObject(i).optString("vehicle_status");
                                    deviceList.online_status = vehicleLists.optJSONObject(i).optString("online_status");
                                    deviceList.glat=vehicleLists.optJSONObject(i).optString("glat");
                                    deviceList.create_time=vehicleLists.optJSONObject(i).optString("create_time");
                                    deviceList.qr_code=vehicleLists.optJSONObject(i).optString("qr_code");
                                    deviceList.remark=vehicleLists.optJSONObject(i).optString("remark");
                                    deviceList.vehicle_status=vehicleLists.optJSONObject(i).optString("vehicle_status");
                                    deviceList.mileage=vehicleLists.optJSONObject(i).optString("mileage");
                                    deviceList.order_number=vehicleLists.optJSONObject(i).optString("order_number");
                                    deviceList.glng=vehicleLists.optJSONObject(i).optString("glng");
                                    deviceList.status=vehicleLists.optJSONObject(i).optString("status");
                                    deviceList.use_status = vehicleLists.optJSONObject(i).optString("use_status");
                                    deviceList.battery = vehicleLists.optJSONObject(i).optInt("battery");
                                    deviceList.condition = vehicleLists.optJSONObject(i).optString("condition");
                                    qrList.add(vehicleLists.optJSONObject(i).optString("qr_code"));
                                    vehicleListAll.add(deviceList);
                                }
                                if (deviceListAdapter != null) {
                                    deviceListAdapter.refresh(vehicleListAll);
                                }
                                refreshLayout.finishRefresh();
                            }
                        }else if ("1001".equals(jsonObject.optString("status"))) {
                            refreshLayout.finishRefresh();
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }else if ("1002".equals(jsonObject.optString("status"))) {
                            refreshLayout.finishRefresh();
                            spUtils.clear();
                            ToastUtil.showToast(jsonObject.optString("message"));
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (vehicleListAll.size() <= 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    deviceList.setVisibility(View.GONE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    deviceList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //锁定车辆
    private void lockCar(String vehicleId) {
        JsonObject lock = new JsonObject();
        lock.addProperty("vehicle_id", vehicleId);
        OkHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.AUDIIT, lock.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            getDeviceList(true);
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });


    }

    //解锁车辆
    private void unLockCar(String vehicleId) {
        JsonObject lock = new JsonObject();
        lock.addProperty("vehicle_id", vehicleId);
        OkHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.AUDIIT, lock.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            getDeviceList(true);
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1001".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1002".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                            SharedUtil.setToken("");
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //解除故障
    private void malfunction(String vehicleId) {
        JsonObject lock = new JsonObject();
        lock.addProperty("vehicle_id", vehicleId);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.MALFATION_CAR, lock.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if ("1000".equals(jsonObject.optString("status"))) {
                            getDeviceList(true);
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1001".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        } else if ("1002".equals(jsonObject.optString("status"))) {
                            ToastUtil.showToast(jsonObject.optString("message"));
                            SharedUtil.setToken("");
                            spUtils.clear();
                            JumpActivitys(LoginActivity.class);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick(R.id.cancel_search)
    public void onViewClicked() {
        finish();
    }
}
